package com.github.tommas.admintpl.bean.filestorage;

import java.io.*;

public class LocalFileStorage extends AbstractFileStorage {
    private final String storageDir;

    public LocalFileStorage(String storageDir) {
        this.storageDir = storageDir;
    }

    @Override
    protected boolean hasDuplicateStorageId(String storageId) {
        File file = new File(storageDir, storageId);
        return file.exists();
    }

    @Override
    protected void doStore(InputStream inputStream, String storageId, String filename) {
        File file = new File(storageDir, storageId);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to store file", e);
        }
    }

    @Override
    public InputStream get(String id) {
        File file = new File(storageDir, id);
        if (!file.exists()) {
            throw new RuntimeException("File not found: " + id);
        }
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("Failed to get file", e);
        }
    }
}
